import { Tree } from '@alifd/next';
import React, { useEffect, useState } from 'react'
import * as api from './api';
import { TreeProps } from '@alifd/next/types/tree';
import { flatToTree } from '@/utils/util';
import { t } from '@lingui/macro';

const TreeNode = Tree.Node;

interface RegionProps extends TreeProps {
  maxLevel?: number; // 最大层级，默认2，如果为1则只能选择城市
  onRegion?: (data: any) => void;
}

/**
 * 通用行政区域选择
 * @returns
 */
const RegionTree = ({ maxLevel = 2, onRegion, ...props }: RegionProps) => {
  const [data, setData] = useState([]);
  const [selected, setSelected] = useState<string>('root');

  useEffect(() => {
    (async () => {
      let res = await api.allRegions(maxLevel);
      // res = res.map((item: any) => ({ data: item, key: item.itemId, label: item.name, icon: <i className="iconfont icon-city" /> }));
      // console.log('>>>res', res);
      res = flatToTree(res);
      // console.log('>>>res2', res);
      setData(res);
    })();
  }, []);

  const handleSelected = (keys: string[], extra: any) => {
    if (!keys.length) return;
    setSelected(keys[0]);
    onRegion?.(extra.node.props.data);
  };

  function getIcon(level) {
    switch (level) {
      case 1:
        return <i className="iconfont icon-city" />;
      case 2:
        return <i className="iconfont icon-flag" />;
      default:
        return <i className="iconfont icon-location" />;
    }
  }


  function renderNode(item: any) {
    const isLeaf = !item.children?.length;
    const level = item.fullId.split(':').length;
    return (
      <TreeNode
        key={item.itemId}
        label={item.name}
        icon={getIcon(level)}
        title={item.name}
        isLeaf={isLeaf}
        data={item}
      >
        {item.children?.map((c: any) => renderNode(c))}
      </TreeNode>
    );
  }

  return (
    <>
      <div>

      </div>
      <Tree
        isNodeBlock={{ indent: 10 }}
        style={{ width: '100%' }}
        selectedKeys={selected ? [selected] : []}
        onSelect={handleSelected}
        defaultExpandedKeys={['root']}
        {...props}
      >
        <TreeNode
          key="root"
          label={t`所有区域`}
          isLeaf={false}
        >
          {data?.map((item: any) => renderNode(item))}
        </TreeNode>
      </Tree>
    </>
  )
}

export default RegionTree
